const axios = require("axios").default;
const randomnumber = require("random-number");
const cookie = require("cookie");
const qs = require("querystring");
const my_user_agent = require("./user-agent");
const Queue = require("promise-queue");
let queue = new Queue(1, Infinity);
queue.push = queue.add;

let east_cookie = null;

function getNewCookie() {
  let user_agent = my_user_agent.getUserAgent();
  return new Promise(async (resolve, reject) => {
    // let first_access = await axios.get("https://mp.eastday.com", {
    //     headers: {
    //         "User-Agent": user_agent
    //     }
    // });
    // //发现原来不需要第一次access...
    try {
      let login_access = await axios.post("https://mp.tt.cn/login", qs.stringify({
        mobile: "18390921465",
        password: "east*65huji",
        authcode: "",
        freelogin: 30
      }), {
          headers: {
            "User-Agent": user_agent
          }
        });
      let JSESSIONID = cookie.parse(login_access.headers['set-cookie'][0])['JSESSIONID'];
      resolve(cookie.serialize("JSESSIONID", JSESSIONID));
    } catch (err) {
      console.error("getNewCookie() Failed!" + err);
      reject(err);
    }

  })
}

/**
 * 
 * @param {String} eastday_cookie 
 */
function verifyCookie(eastday_cookie) {
    return new Promise(async (resolve) => {
        axios.get("http://mp.tt.cn/typeregist.html", {
            headers: {
                cookie: east_cookie,
                "User-Agent": my_user_agent.getUserAgent()
            }
        }).then(axresp => {
            axresp.status == 200 ? resolve(true) : resolve(false);
        }).catch(e => {
            resolve(false);
        });
    })
}

function getCookieInner() {
    return new Promise(async resolve => {
        if (east_cookie) {
            let valid = await verifyCookie(east_cookie);
            if (valid) {
                return resolve(east_cookie);
            }
        }
        try {
            let new_cookie = await getNewCookie();
            east_cookie = new_cookie;
            resolve(east_cookie);
        } catch (err) {
            resolve(null);
        }
    })
}

function getCookie() {
  return new Promise(resolve => {
    queue.push(() => {
      return new Promise(async next => {
        let geted_cookie = await getCookieInner();
        resolve(geted_cookie);
        setTimeout($ => next(), 1);
      })
    })
  })
}



if (!module.parent) {
  getNewCookie().then(cookie => console.log(cookie));
}

module.exports = {
  getNewCookie: getNewCookie,
  getCookie: getCookie
}